package com.company.restaurant.service.handler;

import com.company.restaurant.dto.BaseMessage;
import com.company.restaurant.dto.LoginRequest;
import com.company.restaurant.dto.Protocol;
import com.company.restaurant.dto.util.Packager;
import com.google.gson.Gson;
import io.netty.util.CharsetUtil;

import java.io.*;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * Description of class.
 * Created 3/26/14 7:05 PM
 *
 * @author andrey.rodin@playtech.com
 */

public class TcpClient {

    public static void main(String[] args) {

        LoginRequest loginRequest = new LoginRequest("admin", "12345");
        send(loginRequest);

    }

//    private static byte[] fillMetadata(BaseMessage msg) {
//        Gson gson = new Gson();
//        String json = gson.toJson(msg, msg.getClass());
//        System.out.println(json);
//        byte[] bytesMsg = json.getBytes(CharsetUtil.UTF_8);
//
//        ByteBuffer header = ByteBuffer.allocate(/* MessageID */4 + /* length */4);
//        header.putInt(msg.getCode());
//        header.putInt(bytesMsg.length);
//
//        ByteBuffer fullMsg = ByteBuffer.allocate(header.array().length + bytesMsg.length);
//        fullMsg.put(header.array());
//        fullMsg.put(bytesMsg);
//        return fullMsg.array();
//    }

    private static void send(BaseMessage msg) {
        Socket socket = null;
        OutputStream out = null;
        BufferedReader in = null;
        Gson gson = new Gson();
        String json = gson.toJson(msg, msg.getClass());
        byte[] fullMsg = Packager.toByteArray(msg.getCode(), Protocol.BINARY_JSON_SERIALIZABLE.getId(), json);

        try {
            socket = new Socket("localhost", 55100);
            socket.setKeepAlive(true);
            socket.setTcpNoDelay(true);
            out = socket.getOutputStream();
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        try {
            out.write(fullMsg);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        try {
            while (in.ready()) {
                System.out.println(in.readLine());
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }
}
